class EquipmentController < ApplicationController

def edit_equipment
    @equipment = Equipment.find(params[:id])
    @title = "Editing #{@equipment.model}"

    if @equipment.retired
      flash[:notice] = "Can't edit retired equipment"
      redirect_to :action => "list_equipment"
    end
    if param_posted?(:equipment)
      if @equipment.update_attributes(params[:equipment])
        flash[:notice] = "Equipment #{@equipment.model} updated"
        redirect_to :action => "list_equipment"
      end
    end
end

def add_equipment
    @title = "New Equipment"

    if param_posted?(:equipment)
      @equipment = Equipment.new(params[:equipment])
      @equipment.date_added = Date.new(Time.now.year,Time.now.month,Time.now.day)
      if @equipment.save 
        flash[:notice] = "Equipment #{@equipment.model} created!"
        redirect_to :action => "list_equipment"
      end
    end
end

def list_equipment
  @title = "Equipment"

  @user = Employee.find_by_id(session[:employee_id])

  if params[:search] == nil
      @equipment = Equipment.find(:all)
  else
      @equipment = Equipment.search params[:search]
  end
end

def retire_equipment
  @equipment = Equipment.find(params[:id])
  @title = "Retiring #{@equipment.uniqueid}"

  @user = Employee.find_by_id(session[:employee_id])
  if not @user.is_manager
    if  (Integer(session[:employee_id]) != Integer(params[:id]))
      flash[:notice] = "You must be a manager to complete this operation"
      redirect_to :action=> "list_equipment"
    end
  end

  if param_posted?(:equipment)
    if @equipment.update_attributes(params[:equipment])
      @equipment.retired = 1
      @equipment.date_retired = Date.new(Time.now.year,Time.now.month,Time.now.day)
      if @equipment.save 
        flash[:notice] = "Equipment #{@equipment.uniqueid} retired!"
        redirect_to :action => "list_equipment"
      end
    end
  end
end

def list_retired_equipment
  @title = "Retired Equipment"

  if params[:search] == nil
      @equipment = Equipment.find(:all)
  else
      @equipment = Equipment.search params[:search]
  end
end

def equipment_details
  @equipment = Equipment.find(params[:id])
  @title = "#{@equipment.uniqueid} Details"
end

def retired_equipment_details
  @equipment = Equipment.find(params[:id])
  @title = "#{@equipment.uniqueid} Details"
end

  load "csv.rb"
  
  def add_csv
    if request.post?
        if params[:csv]
            @csv = Csv.new(:csv_file => params[:csv][:uploaded_csv].read)
            if @csv.save!
                session[:csvid] = @csv.id

                data = []    
                @csv_num_cols = 0
                for line in @csv.csv_file do
                    x = line.split(",")
                    if x.length > @csv_num_cols
                        @csv_num_cols = x.length
                    end
                    data.push(line.split(","))
                end

                @csvdata = decode_csv(data) 
                puts @csvdata[0]
                headersPresent = false
                headerfields = [] 
                puts "all the columns!!!:"
                @csvdata[0].each do |col|
                    if Equipment.column_names.include?(col)                        
                        headersPresent = true
#   Indexes in headerfields correspond to columns, the value contained within corresponds to Equipment field names
                        headerfields.push(Equipment.column_names.index(col))
                    else
                        headerfields.push(-1)
                    end
                end

                if headersPresent
                
                    presentCategories = Hash.new
                    Category.find(:all).each do |c|
                        presentCategories[c.name] = c.id
                    end
                
                    rc = 0
                    @csvdata.each do |row|
                        e1 = Equipment.new()
                        cc = 0
                        newCategoryName = ""
                        row.each do |col|
                            if (Integer(headerfields[cc]) > 0) and  rc > 0                             
                                currentFieldName = e1.class.column_names[Integer(headerfields[cc])]
                                if(currentFieldName == "category")
                                    e1[currentFieldName] = presentCategories[col]
                                    newCategoryName = col
                                elsif(currentFieldName.index("cost"))
                                    e1[currentFieldName] = col[/[0-9]+.?[0-9]*/]
                                else
                                    e1[currentFieldName] = col
                                end                    
                            end
                            cc += 1
                        end #end row.each  (Iterating columns)                        
                        e1[:date_added] = Date.new(Time.now.year,Time.now.month,Time.now.day)
                        e1[:created_by] = session[:employee_id]
                        if rc > 0
                            e1.save
                        end
                        rc += 1
# Right now we're not doing anything if the csv specifies a category that does not exist.
                    end #end @csvdata.each (Iterating rows)
                    redirect_to :action => "list_all"
                else
                    redirect_to :action => "map_csv"
                end #endif headersPresent
            else
                flash[:notice] = "error"
            end
        else #csv could not be saved
            redirect_to :controller => "employee", :action => "index"
        end #endif params[:csv]
    end #endif request.post?
  end #end def

  def save_a_csv
    @equip = Equipment.find(:all)
    @csv_result = ""
    for name in Equipment.column_names
        @csv_result += name +","
    end
    @csv_result =  @csv_result[0..@csv_result.length-2] + "\n"
    for e in Equipment.find(:all)
        for name in Equipment.column_names
            fieldval = escapeQuotes(e[name].to_s)
            if fieldval.include? " "
                @csv_result += "\"" + fieldval + "\", "
            else
                @csv_result += fieldval + ", "
            end
         end
        @csv_result = @csv_result[0..@csv_result.length-3] + "\n"
    end
    send_data(@csv_result, :filename => "WPDB_Equipment.csv")
  end

  def no_map_csv
    
  end

  def map_csv
    @csv = Csv.find_by_id(session[:csvid])    
    if @csv
       @equip = Equipment.new()
        @csvdata = []
        @csv_num_cols = 0;
        data = []    
        for line in @csv.csv_file do
            x = line.split(",")
            if x.length > @csv_num_cols
                @csv_num_cols = x.length
            end
            data.push(line.split(","))
        end

        @csvdata = decode_csv(data) 
    else
        flash[:notice] = "No CSV file found, try uploading it again."
        redirect_to :controller => "employee", :action => "index"
    end    

    if request.post? 
        presentCategories = Hash.new
        Category.find(:all).each do |c|
            presentCategories[c.name] = c.id
        end
        newCategories = []

        fieldorder = params[:fieldorder].split(",")        
        rc = 0

        @csvdata.each do |row|
            e1 = Equipment.new()
            cc = 0
            newCategoryName = ""
            row.each do |col|
                if (Integer(fieldorder[cc]) > 0)
                    currentFieldName = e1.class.column_names[Integer(fieldorder[cc])]           
                    if(currentFieldName == "category")
                        e1[currentFieldName] = presentCategories[col]
                        newCategoryName = col
                    elsif(currentFieldName.index("cost"))
                        e1[currentFieldName] = col[/[0-9]+.?[0-9]*/]
                    else
                        e1[currentFieldName] = col
                    end                    
                end
                cc += 1
            end
            rc += 1
            e1[:date_added] = Date.new(Time.now.year,Time.now.month,Time.now.day)
            e1[:created_by] = session[:employee_id]

            if e1.save and e1[:category] == nil and newCategoryName != ""
                newCategories.push([e1.id, newCategoryName])
            end
        end
        @csv.destroy
        if(newCategories.size == 0)
            flash[:notice] = "Equipment uploaded"
            redirect_to :controller => "equipment", :action => "list_all"
        else
            session[:categories] = newCategories
            redirect_to :controller => "category", :action => "resolve_categories"
        end
    end
  end

private
  def param_posted?(symbol)
    request.post? and params[symbol]
  end

end

